package com.ldg.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.ld.utils.PageUtils;
import com.ldg.manager.dao.SpecificationOptionDao;
import com.ldg.manager.entity.SpecificationOptionEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.utils.Query;

import com.ldg.manager.dao.TypeTemplateDao;
import com.ldg.manager.entity.TypeTemplateEntity;
import com.ldg.manager.service.TypeTemplateService;

import javax.annotation.Resource;


@Service("typeTemplateService")
public class TypeTemplateServiceImpl extends ServiceImpl<TypeTemplateDao, TypeTemplateEntity> implements TypeTemplateService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SpecificationOptionDao specificationOptionDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TypeTemplateEntity> page = this.page(
                new Query<TypeTemplateEntity>().getPage(params),
                new QueryWrapper<TypeTemplateEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<TypeTemplateEntity> findAll() {
        //查询模板
        List<TypeTemplateEntity> list = this.list();
        //遍历模板
        for (TypeTemplateEntity entity : list) {
        //以模板id为key，品牌列表为值存入redis
            redisTemplate.boundHashOps("brandList").put(entity.getId(),entity.getBrandIds());
            //得到规格列表
            String specIds = entity.getSpecIds();
            //转换为list<Map>形式
            List<Map> specMap = JSON.parseArray(specIds, Map.class);
            //遍历maps，将规格选项放入
            for (Map map : specMap) {
                //得到规格id
                String id = (String) map.get("id");
                //根据规格id查询规格选项
                List<SpecificationOptionEntity> options = specificationOptionDao.selectList(new QueryWrapper<SpecificationOptionEntity>().eq("spec_id", id));
                //放入map中
                map.put("options",options);
            }
            //将规格和规格选项放入redis
            redisTemplate.boundHashOps("specList").put(entity.getId(),JSON.toJSONString(specMap));
        }
        return list;
    }

}
